package com.bt.lms.ui.action.enp;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.EnpBizTypeConstant;
import com.bt.lms.entity.EnrollmentPlan;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.action.enp.vo.AddEnpVo;
import com.bt.lms.ui.page.common.action.pageenp.EnpLabAction;
import com.bt.lms.ui.page.enp.AddEnrollment;
import com.bt.lms.ui.page.enp.EnrollmentPlanList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 保存新增招生计划（验证）事件
 *
 * @author lumengli
 */
public class SaveAddEnpPlanAction implements EventHandler {

    /**
     * 新增招生计划
     */
    private AddEnrollment addEnrollment;


    public SaveAddEnpPlanAction(AddEnrollment addEnrollment) {
        this.addEnrollment = addEnrollment;

    }

    @Override
    public void handle(Event event) {
        //1.获取用户输入,返回定义的Vo对象
        AddEnpVo addEnpVo = getInParams();
        //2.验证用户输入，返回验证的消息结果
        String validateMsg = validateInParam(addEnpVo);
        //3.组包
        byte[] bytes = null;
        if (null == validateMsg) {
            bytes = handle2ReqMsg(addEnpVo);
        } else {
            //提示，程序终止
            return;
        }

        //4.组网
        Socket socket = getNet();
        //5.发送消息
        boolean flag = send(socket, bytes);

    }

    /**
     * 发送消息
     * 1.将消息转为字节流
     * 2.发送
     *
     * @param socket 发生的socket
     * @param bytes  要发送的消息
     * @return
     */
    private boolean send(Socket socket, byte[] bytes) {

        //发送消息
        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes); //写
            out.flush();//冲刷，立刻发出去

            //接收回应消息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf); //读
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();

        } catch (IOException e) {
//            throw new RuntimeException(e);
        }
        return true;
    }


    /**
     * 获取网络
     *
     * @return socket
     */
    private Socket getNet() {
        //ip和端口号
        String serverIp = "127.0.0.1";
        int serverPort = 8888;
        Socket socket = null;
        try {
            socket = new Socket(serverIp, serverPort);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return null;
        }

        return socket;
    }

    /**
     * 将用户输入的信息处理成我们规定的请求信息
     *
     * @param addEnpVo 用户输入的消息
     * @return 请求消息
     */
    private byte[] handle2ReqMsg(AddEnpVo addEnpVo) {

        //消息
        ReqMsg reqMsg = new ReqMsg();
        //课程信息实体类
        EnrollmentPlan enrollmentPlan = new EnrollmentPlan();
        //业务类型
        reqMsg.setBizType(EnpBizTypeConstant.ENP_PLAN_ADD);
        //vo转实体类
        try {
            //属性复制
            BeanUtils.copyProperties(enrollmentPlan, addEnpVo);
            enrollmentPlan.setId(1L);
            enrollmentPlan.setTeachPlanId(2L);
            //转JSON
            String enpStr = JSON.toJSONString(enrollmentPlan);
            //数据带走
            reqMsg.setData(enpStr);

        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        //转总数组
        byte[] bytes = reqMsg.toBytes();

        return bytes;
    }

    /**
     * 2.验证
     *
     * @param addEnpVo 用户输入的数据
     * @return 验证的结果
     */
    private String validateInParam(AddEnpVo addEnpVo) {
        String tooltip = "";
        //招生计划编号
        String code = addEnpVo.getCode();
        if (code.equals("")) {
            tooltip += "请填写招生计划编号\r\n";
        } else {
            if (code.length() > 18) {
                tooltip += "招生计划编号在1-18位\r\n";

            }
        }

        //招生计划名称
        String name = addEnpVo.getPlanName();
        if (name.equals("")) {
            tooltip += "请输入计划名称\r\n";
        } else {
            if (name.length() > 24) {
                tooltip += "请输入正确的计划名称，最长不能超过24位\r\n";
            }
        }

        //计划内容
        String content = addEnpVo.getPlanContent();
        if (content.equals("")) {
            tooltip += "请输入招生内容\r\n";

        } else {
            if (content.length() > 255) {
                tooltip += "请输入正确的招生内容，最长不能超过255位\r\n";
            }
        }


        //招生层次
        //招生专业

        //招生人数
        String peoNo = addEnpVo.getPopulation();
        if (peoNo.equals("")) {
            tooltip += "请输入招生人数\r\n";
        } else {
            try {
                int i1 = Integer.parseInt(peoNo);
                if (peoNo.length() > 6) {
                    tooltip += "请输入正确的招生人数，最长不能超过6位\r\n";
                }
            } catch (NumberFormatException e) {
                tooltip += "请输入数字（招生人数）\r\n";
            }
        }


        //学习中心
        //关联教学计划


        //学费标准
        String tuitionFee = addEnpVo.getTuitionFee();//值
        Integer tuitionFeeUnit = addEnpVo.getTuitionStandard();
        if (tuitionFee.equals("")) {
            tooltip += "请输入学费标准\r\n";
        } else {
            if (tuitionFeeUnit == 1) {
                int i1 = 0;
                try {
                    i1 = Integer.parseInt(tuitionFee);
                    if (i1 > 30000) {
                        tooltip += "请输入正确的学费（学年），最长不能超过30000元\r\n";
                    }
                } catch (NumberFormatException e) {
                    tooltip += "请输入数字（学费）\r\n";
                }
            }
            if (tuitionFeeUnit == 2) {
                int i1 = 0;
                try {
                    i1 = Integer.parseInt(tuitionFee);
                    if (i1 > 3000) {
                        tooltip += "请输入正确的学费（学分），最长不能超过3000元\r\n";
                    }
                } catch (NumberFormatException e) {
                    tooltip += "请输入数字（学费）\r\n";
                }
            }

            if (tuitionFeeUnit == 3) {
                int i1 = 0;
                try {
                    i1 = Integer.parseInt(tuitionFee);
                    if (i1 > 300) {
                        tooltip += "请输入正确的学制（学时），最长不能超过300元\r\n";
                    }
                } catch (NumberFormatException e) {
                    tooltip += "请输入数字（学费）\r\n";
                }
            }
        }
        //报名开始时间
        LocalDate startDate = addEnpVo.getStartTime();
        if (startDate == null) {
            tooltip += "请选择报名开始时间\r\n";
        }

        //报名结束时间
        LocalDate stopDate = addEnpVo.getStopTime();
        if (stopDate == null) {
            tooltip += "请选择报名结束时间\r\n";
        }
        if (!(stopDate == null)) {
            int startTimeYear = startDate.getYear();//开始时间
            int stopTimeYear = stopDate.getYear();//结束时间


            if (stopTimeYear >= startTimeYear) {//不能在报名开始时间之前
                int startTimeMonth = startDate.getMonthValue();
                int stopTimeMonth = stopDate.getMonthValue();
                if (stopTimeMonth >= startTimeMonth) {
                    int startDay = startDate.getDayOfMonth();
                    int stopDay = stopDate.getDayOfMonth();


                } else {
                    tooltip += "请选择正确的报名结束时间，结束时间不能小于开始时间（月）\r\n";
                }

            } else {
                tooltip += "请选择正确的报名结束时间，结束时间不能小于开始时间（年）\r\n";
            }
        }
        //报名方式
        //报名地点(省)
        //报名地点（市）
        //报名地点（详细地址）
        String address = addEnpVo.getRegPlace();
        if (address.equals("")) {
            tooltip += "请输入报名地点\r\n";
        } else {
            if (address.length() > 24) {
                tooltip += "请输入正确的报名地点，最长不能超过24位\r\n";
            }
        }
        //联系人
        String contact = addEnpVo.getContact();
        if (contact.equals("")) {
            tooltip += "请输入联系人\r\n";
        } else {
            if (contact.length() > 32) {
                tooltip += "请输入正确的联系人，最长不能超过32位\r\n";
            }
        }

        //电话
        String phone = addEnpVo.getPhone();
        if (phone.equals("")) {
            tooltip += "请输入电话号码\r\n";
        } else {
            if (phone.length() != 11) {
                tooltip += "请输入正确的电话号码，最长不能超过11位\r\n";
            }
        }

        //电子邮箱
        String email = addEnpVo.getEmail();
        Pattern emailCompile = Pattern.compile("^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$");
        Matcher matcher = emailCompile.matcher(email);
        boolean matches = matcher.matches();

        if (!matches) {
            tooltip += "请输入正确的电子邮箱\r\n";

        }

        //报名材料
        List enpMatType = addEnpVo.getRegistrationType();
        int size = enpMatType.size();
        if (size == 0) {
            tooltip += "请选择报名材料\r\n";
        }


        //报名事项
        String matter = addEnpVo.getEnpItem();
        if (!matter.equals("")) {
            if (matter.length() > 255) {
                tooltip += "请输入正确的报名事项，最长不能超过255位\r\n";

            }
        }
        //毕/结业相关事项
        String graduate = addEnpVo.getGraduateRelatedMatters();
        if (!graduate.equals("")) {
            if (graduate.length() > 255) {
                tooltip += "请输入正确的毕/结业相关事项，最长不能超过255位\r\n";

            }
        }

        //补充说明
        String replenish = addEnpVo.getReplenishExplain();
        if (!replenish.equals("")) {
            if (replenish.length() > 255) {
                tooltip += "请输入正确的补充说明，最长不能超过255位\r\n";

            }
        }


        //处理返回
        if (tooltip.equals("")) {
            tooltip = null;
        }

        // 总窗口
        if (!(tooltip == null)) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(tooltip);
            alert.show();
        } else {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("成功");
            alert.setContentText("保存成功");
            alert.show();

            EnrollmentPlanList enrollmentPlanList = new EnrollmentPlanList();
            Pane pane = EnpLabAction.pageSkipInfo.getPane();
            Integer index = EnpLabAction.pageSkipInfo.getIndex();
            pane.getChildren().set(index, enrollmentPlanList);
        }


        return tooltip;
    }


    /**
     * 1.获取用户的输入
     *
     * @return 用户输入的数据
     */
    private AddEnpVo getInParams() {

        //编号
        TextField codeTF = (TextField) this.addEnrollment.lookup("#codeTF");
        //名称
        TextField nameTf = (TextField) this.addEnrollment.lookup("#nameTf");
        //内容
        TextArea contentTA = (TextArea) this.addEnrollment.lookup("#contentTA");
        //招生层次
        ComboBox levelCom = (ComboBox) this.addEnrollment.lookup("#levelCom");
        //招生专业
        ComboBox specialtyCom = (ComboBox) this.addEnrollment.lookup("#specialtyCom");
        //招生人数
        TextField enPopulationTF = (TextField) this.addEnrollment.lookup("#enPopulationTF");
        //学费标准（值）
        TextField tuitionTf = (TextField) this.addEnrollment.lookup("#tuitionTf");
        //学费标准（单位）
        ComboBox tuitionCom = (ComboBox) this.addEnrollment.lookup("#tuitionCom");
        //报名开始时间
        DatePicker startDateDp = (DatePicker) this.addEnrollment.lookup("#startTimeDp");
        //报名结束时间
        DatePicker stopDateDp = (DatePicker) this.addEnrollment.lookup("#stopTimeDp");

        //报名方式
        ComboBox regModeCom = (ComboBox) this.addEnrollment.lookup("#regModeCom");


        //报名地点（省）
        ComboBox enpLocationCom = (ComboBox) this.addEnrollment.lookup("#enpLocationCom");
        //报名地点（市）
        ComboBox areaCom = (ComboBox) this.addEnrollment.lookup("#areaCom");
        //报名地点（详细地址）
        TextField enrollmentLocationTF = (TextField) this.addEnrollment.lookup("#enrollmentLocationTF");
        //联系人
        TextField ltdContactTF = (TextField) this.addEnrollment.lookup("#ltdContactTF");
        //电话
        TextField phoneTF = (TextField) this.addEnrollment.lookup("#phoneTF");
        //电子邮箱
        TextField emailTF = (TextField) this.addEnrollment.lookup("#emailTF");

        //报名材料
        List<Integer> applyType = new ArrayList<>();

        CheckBox idBox = (CheckBox) this.addEnrollment.lookup("#idBox");//身份证
        //如果身份证被选中
        if (idBox.isSelected()) {

            applyType.add(1);//加到集合里
        }
        CheckBox picBox = (CheckBox) this.addEnrollment.lookup("#picBox");//照片
        if (picBox.isSelected()) {

            applyType.add(2);
        }
        CheckBox diplomaBox = (CheckBox) this.addEnrollment.lookup("#diplomaBox");//学历证明
        if (diplomaBox.isSelected()) {

            applyType.add(3);
        }
        CheckBox degreeBox = (CheckBox) this.addEnrollment.lookup("#degreeBox");//学位证明
        if (degreeBox.isSelected()) {

            applyType.add(4);
        }
        CheckBox bodyExaBox = (CheckBox) this.addEnrollment.lookup("#bodyExaBox");//体检报告
        if (bodyExaBox.isSelected()) {

            applyType.add(5);
        }
        CheckBox restsBox = (CheckBox) this.addEnrollment.lookup("#restsBox");//其他
        if (restsBox.isSelected()) {
            applyType.add(6);
        }


        //报名事项
        TextArea itemsTA = (TextArea) this.addEnrollment.lookup("#itemsTA");
        //毕/结业相关事项
        TextArea graduateTA = (TextArea) this.addEnrollment.lookup("#graduateTA");
        //补充说明
        TextArea replenishTA = (TextArea) this.addEnrollment.lookup("#replenishTA");


        //封装成Vo对象
        AddEnpVo addEnpVo = new AddEnpVo();
        //编号
        String codeStr = codeTF.getText().trim();//去空格
        addEnpVo.setCode(codeStr);
        //名称
        String nameStr = nameTf.getText().trim();
        addEnpVo.setPlanName(nameStr);
        //内容
        String contentStr = contentTA.getText().trim();
        addEnpVo.setPlanContent(contentStr);

        //招生层次
        String level = (String) levelCom.getValue();
        Integer levelInt = 0;
        if (level.equals("不限")) {
            levelInt = 1;
        }
        if (level.equals("免费师范生")) {
            levelInt = 2;
        }
        if (level.equals("免费师范生教育博士")) {
            levelInt = 3;
        }

        if (level.equals("职后教师")) {
            levelInt = 4;
        }

        if (level.equals("其他")) {
            levelInt = 5;
        }
        addEnpVo.setLevel(levelInt);

        //招生专业
        String specialty = (String) specialtyCom.getValue();
        Integer specialtyInt = 0;
        if (specialty.equals("不限")) {
            specialtyInt = 1;
        }
        addEnpVo.setMajor(specialtyInt);

        //招生人数
        String enPopulation = enPopulationTF.getText().trim();
        addEnpVo.setPopulation(enPopulation);

        //学习中心

        //关联教学计划


        //学费标准(值)
        String tuitionValue = tuitionTf.getText().trim();
        addEnpVo.setTuitionFee(tuitionValue);
        //学费标准（单位）
        String tuitionU = (String) tuitionCom.getValue();
        Integer tuitionUInt = 0;
        if (tuitionU.equals("元/学年")) {
            tuitionUInt = 1;
        }
        if (tuitionU.equals("元/学分")) {
            tuitionUInt = 2;
        }
        if (tuitionU.equals("元/学时")) {
            tuitionUInt = 3;
        }
        addEnpVo.setTuitionStandard(tuitionUInt);
        //报名开始时间
        LocalDate startDate = startDateDp.getValue();
        addEnpVo.setStartTime(startDate);
        //报名结束时间
        LocalDate stopDate = stopDateDp.getValue();
        addEnpVo.setStopTime(stopDate);


        //报名事项
        String regModeStr = (String) regModeCom.getValue();
        Integer regModeInt = 0;
        if (regModeStr.equals("线上")) {
            regModeInt = 1;
        }
        if (regModeStr.equals("线下")) {
            regModeInt = 2;
        }
        if (regModeStr.equals("都可以")) {
            regModeInt = 3;
        }
        addEnpVo.setRegMode(regModeInt);

        //报名地点(省)
        //报名地点（市）
        //报名地点（详细地址）
        String enrollmentLocation = enrollmentLocationTF.getText().trim();
        addEnpVo.setRegPlace(enrollmentLocation);
        //联系人
        String ltdContact = ltdContactTF.getText().trim();
        addEnpVo.setContact(ltdContact);

        //电话
        String phone = phoneTF.getText().trim();
        addEnpVo.setPhone(phone);
        //电子邮箱
        String email = emailTF.getText().trim();
        addEnpVo.setEmail(email);
        //报名材料
        addEnpVo.setRegistrationType(applyType);

        //报名事项
        String items = itemsTA.getText().trim();
        addEnpVo.setEnpItem(items);
        //毕/结业相关事项
        String graduate = graduateTA.getText().trim();
        addEnpVo.setGraduateRelatedMatters(graduate);
        //补充说明
        String replenish = replenishTA.getText().trim();
        addEnpVo.setReplenishExplain(replenish);


        return addEnpVo;
    }


    /**
     * short 转 byte
     *
     * @param value
     * @return
     */
    public byte[] shortToBytes(short value) {
        byte[] returnByteArray = new byte[2];
        returnByteArray[0] = (byte) (value & 0xff);
        returnByteArray[1] = (byte) ((value >>> 8) & 0xff);
        return returnByteArray;
    }

    /**
     * 将int数值转换为占四个字节的byte数组，本方法适用于(高位在前，低位在后)的顺序。  和bytesToInt2（）配套使用
     */
    public static byte[] intToBytes(int value) {
        byte[] src = new byte[4];
        src[0] = (byte) ((value >> 24) & 0xFF);
        src[1] = (byte) ((value >> 16) & 0xFF);
        src[2] = (byte) ((value >> 8) & 0xFF);
        src[3] = (byte) (value & 0xFF);
        return src;
    }


}

